package com.zq.it.cms.web.back;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zq.it.cms.common.Constants;
import com.zq.it.cms.common.Context;
import com.zq.it.cms.common.security.CredentialsDigest;
import com.zq.it.cms.domain.User;
import com.zq.it.cms.service.UserService;

/**
 * @author zhengqiang
 * @description 工作台
 */
@Controller
@RequestMapping("/dashboard")
public class DashboardController {

	@Autowired
	private UserService userService;
	@Autowired
	private CredentialsDigest credentialsDigest;
	
	@RequestMapping("/welcome")
	public String welcome(ModelMap model){
		return "dashboard/welcome";
	}
	
	@RequestMapping("/password_edit")
	@RequiresPermissions("dashboard:password:edit")
	public String password_edit(ModelMap model){
		User user = Context.getCurrentUser();
		model.put("user", user);
		return "dashboard/password";
	}
	
	@RequestMapping("/password_update")
	@RequiresPermissions("dashboard:password:update")
	public String password_update(String oldPassword, String password, ModelMap model, RedirectAttributes ra){
		User user = Context.getCurrentUser();
		user = userService.findById(user.getId());
		if(credentialsDigest.matches(user.getPassword(), oldPassword, user.getSaltBytes())){
			userService.updatePassword(user.getId(), password);
			ra.addFlashAttribute(Constants.STATUS, Constants.OPERATION_SUCCESS);
		}else{
			ra.addFlashAttribute(Constants.STATUS, Constants.OPERATION_FAILURE);
		}
		return "redirect:password_edit";
	}
}
